'use client'
import { FC, useEffect, useRef, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import gsap from 'gsap'
import { usePathname } from 'next/navigation'
import { useMount, useSize, useToggle } from "ahooks"
import { twMerge } from "tailwind-merge"

gsap.registerPlugin(ScrollTrigger)

const data = [
  {
    path: '/',
    name: '首页'
  },
  {
    path: '/product-service',
    name: '产品与服务'
  },
  {
    path: '/news',
    name: '资讯与资料'
  },
  {
    path: '/contact',
    name: '联系我们'
  }
]

const HeaderNav: FC = () => {
  const pathname = usePathname() 
  const [indicatorLeft, setIndicatorLeft] = useState(0)
  const [indicatorWidth, setIndicatorWidth] = useState(56)
  const [visible, { toggle }] = useToggle(false)
  const [bodyElement, setBodyElement] = useState(null)
  const size = useSize(bodyElement)
  const time = useRef<number>(new Date().getTime())

  const handleTabClick = (e: any) => {
    setIndicatorLeft(e.currentTarget.offsetLeft)
    setIndicatorWidth(e.currentTarget.offsetWidth)
  }

  const handleToggle = () => {
    const now = new Date().getTime()
    if (now - time.current < 1000) return
    time.current = now
    if (visible) {
      gsap.to('.slide', {
        opacity: 0,
        y: -10,  // 恢复位移
        duration: 0.1,
        stagger: { each: 0.1, from: 'end' },
        ease: "power2.in",
        onComplete: () => {
          gsap.to('.submenu', {
            yPercent: '-100',
            opacity: '0',
            duration: 0.4,
            ease: 'power4.in',
            onComplete: () => {
              gsap.set('.submenu', { display: 'none' })
            }
          })
        }
      })
    } else {
      gsap.to('.submenu', {
        display: 'block',
        opacity: 1,
        yPercent: '0',
        duration: 0.4,
        ease: "power4.out",
        onComplete: () => {
          gsap.to('.slide', {
            opacity: 1,
            y: 0,  // 恢复位移
            duration: 0.4,
            stagger: 0.1, // 每个菜单项相隔0.2秒依次出现
            ease: "power2.out",
          })
        }
      })
    }
    toggle()
  }
  
  useEffect(() => {
    gsap.set('.submenu', {
      display: 'none',
      opacity: 0,
      yPercent: '-100'
    })
    gsap.set('.slide', {
      opacity: 0,
      y: 10,
    })
    if (window.innerWidth < 768) return
    const showAnim = gsap.from('.main-tool-bar', { 
      yPercent: -100,
      paused: true,
      duration: 0.2,
      boxShadow: 'none'
    }).progress(1);
    
    ScrollTrigger.create({
      start: "max",
      end: "max",
      onUpdate: (self) => {
        self.direction === -1 ? showAnim.play() : showAnim.reverse()
      }
    });
  }, [pathname])

  useEffect(() => {
    if ((size?.width || 0) > 768 && visible) {
      handleToggle()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [size?.width])

  useMount(() => {
    const li = document.querySelectorAll('.menu li') as any

    if (pathname === '/') {
      setIndicatorLeft(li[0]?.offsetLeft)
      setIndicatorWidth(li[0]?.offsetWidth)
    } else if (pathname === '/product-service') {
      setIndicatorLeft(li[1]?.offsetLeft)
      setIndicatorWidth(li[1]?.offsetWidth)
    } else if (pathname === '/news') {
      setIndicatorLeft(li[2]?.offsetLeft)
      setIndicatorWidth(li[2]?.offsetWidth)
    } else if (pathname === '/contact') {
      setIndicatorLeft(li[3]?.offsetLeft)
      setIndicatorWidth(li[3]?.offsetWidth)
    }
  })
  
  useEffect(() => {
    // @ts-ignore
    setBodyElement(document.querySelector('body'))
  }, [])
  
  return (
    <>
      <div className={twMerge("main-tool-bar sticky top-0 left-0 right-0 bg-white z-50 h-[50px] md:h-[70px]", pathname !== '/' && 'shadow-lg')}>
        <div className="w-[1650px] max-1650:w-auto px-[10px] lg:px-[20px] 2xl:px-0 mx-auto flex justify-between items-center h-full box-border">
          <div className="w-[242px] lg:w-[340px] h-[24px] lg:h-[34px] relative">
            <Link href='/'>
              <Image src="/images/logo.png" alt="logo" fill className="object-contain" />
            </Link>
          </div>
          <div className="relative h-full hidden md:block">
            <ul className="menu flex items-center space-x-[10px] lg:space-x-[20px] h-full">
              <li className="cursor-pointer transition-colors hover:bg-[#f5f5f5] rounded-sm h-full relative" onClick={handleTabClick}>
                <Link className="p-[10px] text-sm lg:text-[18px] text-[#333] hover:text-[#000] h-full flex items-center justify-center" href="/">首页</Link>
              </li>
              <li className="cursor-pointer transition-colors hover:bg-[#f5f5f5] rounded-sm h-full relative" onClick={handleTabClick}>
                <Link className="p-[10px] text-sm lg:text-[18px] text-[#333] hover:text-[#000] h-full flex items-center justify-center" href="/product-service">产品与服务</Link>
              </li>
              {/* <li className="cursor-pointer transition-colors hover:bg-[#f5f5f5] rounded-sm h-full relative" onClick={handleTabClick}>
                <Link className="p-[10px] text-sm lg:text-[18px] text-[#333] hover:text-[#000] h-full flex items-center justify-center" href="/case">学员案例</Link>
              </li> */}
              <li className="cursor-pointer transition-colors hover:bg-[#f5f5f5] rounded-sm h-full relative" onClick={handleTabClick}>
                <Link className="p-[10px] text-sm lg:text-[18px] text-[#333] hover:text-[#000] h-full flex items-center justify-center" href="/news">资讯与资料</Link>
              </li>
              <li className="cursor-pointer transition-colors hover:bg-[#f5f5f5] rounded-sm h-full relative" onClick={handleTabClick}>
                <Link className="p-[10px] text-sm lg:text-[18px] text-[#333] hover:text-[#000] h-full flex items-center justify-center" href="/contact">联系我们</Link>
              </li>
            </ul>
            <div className='absolute top-0 left-0 right-0 h-[3px] bg-[#0C4E99] ease-out transition-all duration-500' style={{ left: indicatorLeft, width: indicatorWidth }}></div>
          </div>
          <div className='md:hidden size-[20px] flex-col relative z-50' onClick={handleToggle}>
            {/* <i className='bg-[url(/images/menu.png)] bg-no-repeat bg-contain text-3xl cursor-pointer text-black/80 size-full'></i > */}
            <i className={twMerge("w-full h-[2px] absolute top-[5px] bg-black/60 block transition-all duration-500", visible && 'rotate-[45deg] top-[9px]')}></i>
            <i className={twMerge("w-full h-[2px] absolute top-[13px] bg-black/60 block transition-all duration-500", visible && 'rotate-[-45deg] top-[9px]')}></i>
          </div>
          <div className='submenu fixed md:hidden left-0 top-0 right-0 h-screen bg-white z-[40] px-[20px] shadow-lg' onClick={handleToggle}>
            <ul className='text-white/90 pt-[40px]'>
              {data?.map((item, index) => (
                <li key={index} className={twMerge('slide opacity-0 w-full text-base flex items-center border-b', index === data.length - 1 && 'border-b-0')} onClick={() => handleTabClick(index)}>
                  <Link href={item.path} className="block py-[12px] w-full text-black/70">{item.name}</Link>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </>
  )
}

export default HeaderNav
